{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf2e60ae-f848-4ffd-83d9-135a6bd1059c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "import requests\n",
    "import jsonlines\n",
    "from tqdm import tqdm\n",
    "import time\n",
    "from multiprocessing import Pool\n",
    "from functools import partial\n",
    "\n",
    "from tenacity import (\n",
    "    retry,\n",
    "    stop_after_attempt,\n",
    "    wait_random_exponential,\n",
    "    RetryError\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "93c2e2f6-9fa4-4fbf-91f9-8de7119cb101",
   "metadata": {},
   "outputs": [],
   "source": [
    "os.environ['WENXIN_KEY'] = \"your wenxin key\"\n",
    "@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(5))\n",
    "def ernie_bot_api(**kwargs):\n",
    "    try:\n",
    "        if not os.environ.get('WENXIN_KEY'):\n",
    "            print(f\"Environment variable 'WENXIN_KEY' not exists. Please set\")\n",
    "            return\n",
    "        url = f\"your wenxin query url\"\n",
    "        payload = json.dumps({\n",
    "            \"messages\": kwargs[\"messages\"],\n",
    "            \"system\": kwargs.get(\"system\", None),\n",
    "        })\n",
    "        headers = {\n",
    "            'Content-Type': 'application/json'\n",
    "        }\n",
    "        response = requests.request(\"POST\", url, headers=headers, data=payload)\n",
    "        if kwargs.get('stream', False):\n",
    "            result = []\n",
    "            for line in response.iter_lines():\n",
    "                content = line.decode(\"utf-8\")[5:]\n",
    "                if len(content.strip()) == 0:\n",
    "                    continue\n",
    "                result.append(json.loads(content)['result'])\n",
    "            generation = \"\".join(result)\n",
    "        else:\n",
    "            generation = json.loads(response.text)['result']\n",
    "        return generation\n",
    "    except Exception as e:\n",
    "        print(response.text)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "a8dd1370-d55b-4b1b-b6b7-cf077694e13b",
   "metadata": {},
   "outputs": [],
   "source": [
    "def process(item):\n",
    "    message = []\n",
    "    for prompt in item['prompts']:\n",
    "        message.append({\"role\": \"user\", \"content\": prompt})\n",
    "        answer = ernie_bot_api(messages=message, system=item['system'])\n",
    "        message.append({\"role\": \"assistant\", \"content\": answer})\n",
    "    message = [{\"role\": \"system\", \"content\": item['system']}] + message\n",
    "    item['messages'] = message\n",
    "    return item"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4c8c03fe-2a89-4fc3-8376-75d1d20463cf",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = list(jsonlines.open(\"../data/wiki_roleplay_multilingual_test_input_w_evidence.jsonl\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a867c95f-aa47-4ed1-a57d-d44351dbce5c",
   "metadata": {},
   "outputs": [],
   "source": [
    "results = []\n",
    "pbar = tqdm(total=len(data))\n",
    "for item in data:\n",
    "    pbar.update(1)\n",
    "    results.append(process(item))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "93954aa1-9ba1-4ab2-8cba-e4c9e829247f",
   "metadata": {},
   "outputs": [],
   "source": [
    "with jsonlines.open(f\"../data/results/wiki_roleplay_multilingual_test_input_w_evidence_wenxin_output.jsonl\", \"w\") as f:\n",
    "    for each in results:\n",
    "        f.write(each)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
